package com.meida.module.bus.provider.handler;

import com.apistd.uni.Uni;
import com.apistd.uni.UniException;
import com.apistd.uni.UniResponse;
import com.apistd.uni.sms.UniMessage;
import com.apistd.uni.sms.UniSMS;
import com.meida.common.base.entity.EntityMap;
import com.meida.common.base.handler.SmsSendHandler;
import com.meida.common.utils.JsonUtils;
import com.meida.common.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;


@Component
public class UniSmsHandler implements SmsSendHandler {

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public void send(String mobile, Integer code, String areaCode) {
        EntityMap map = redisUtils.getConfigMap("SMS_CONFIG");
        String accessKeyId = map.get("accessKey");
        String signName = map.get("signName");
        String smsTplCode = map.get("smsTplCode");
        Uni.init(accessKeyId);
        Map<String, String> templateData = new HashMap<>();
        templateData.put("code", code.toString());
        /* 构建信息 */
        UniMessage message = UniSMS.buildMessage()
                .setTo(areaCode+mobile)
                .setSignature(signName)
                .setTemplateId(smsTplCode)
                .setTemplateData(templateData);

        // 发送短信
        try {
            UniResponse res = message.send();
            System.out.println(JsonUtils.beanToJson(res));
        } catch (UniException e) {
            System.out.println("Error: " + e);
            System.out.println("RequestId: " + e.requestId);
        }
    }

    @Override
    public void sendSms(String mobile, String tplCode, Map<String, Object> params) {
        EntityMap map = redisUtils.getConfigMap("SMS_CONFIG");
        String accessKeyId = map.get("accessKey");
        String smsTplCode = map.get("smsTplCode");
        String signName = map.get("signName");
        Uni.init(accessKeyId);
        Map<String, String> templateData = new HashMap<>();
        for (Map.Entry entry : params.entrySet()) {
            if (entry.getValue() instanceof String) {
                templateData.put(entry.getKey().toString(), (String) entry.getValue());
            }
        }
        /* 构建信息 */
        UniMessage message = UniSMS.buildMessage()
                .setTo(mobile)
                .setSignature(signName)
                .setTemplateId(smsTplCode)
                .setTemplateData(templateData);
        // 发送短信
        try {
            UniResponse res = message.send();
            System.out.println(res);
        } catch (UniException e) {
            System.out.println("Error: " + e);
            System.out.println("RequestId: " + e.requestId);
        }

    }

}
